import React, { useState } from 'react'
import { useQuery } from 'react-query'
import { PeoplePage } from '../types'
import { Person } from './Person'

const fetchPeople = async (page: number): Promise<PeoplePage> => {
  const res = await fetch(`http://swapi.dev/api/people/?page=${page}`)
  return res.json()
}

export const People = () => {
  const [page, setPage] = useState<number>(1)
  const { data, isLoading, isError, isSuccess, isFetching } = useQuery(
    ['people', page],
    () => fetchPeople(page),
    {
      keepPreviousData: true,
    }
  )
  return (
    <div>
      <h2>People</h2>
      {isError && <div>Error Fetching Data</div>}
      {isLoading && <div>Loading Data</div>}
      {isSuccess && (
        <>
          <button
            disabled={!data?.previous}
            onClick={() => !isFetching && setPage(page - 1)}
          >
            prev
          </button>
          <span>{page}</span>
          <button
            disabled={!data?.next}
            onClick={() => !isFetching && setPage(page + 1)}
          >
            next
          </button>
          <div>
            {data?.results.map((person) => (
              <Person key={person.name} person={person} />
            ))}
          </div>
        </>
      )}
    </div>
  )
}
